import sun.misc.PerfCounter;

/**
 * 打破双亲机制
 *
 * @author <a href='mailto:maruichao52@gmail.com'>MRC</a>
 * @since 2021/4/21
 */
public class MyClassLoaderPlus extends MyClassLoader {

    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {

        System.out.println("开始加载：name=" + name);

        Class<?> c = findLoadedClass(name);
        long t0 = System.nanoTime();

        try {
            // 如果以string 结尾。则打破双亲委托，其他的还是按照双亲委托
            if (null == c && name.endsWith("String")) {
                c = findClass(name);
            } else {
                c = getParent().loadClass(name);
            }
        } catch (Exception e) {

        }
        // 打破从父类加载的原则，直接从当前类加载。
        if (null == c) {
            long t1 = System.nanoTime();
            c = findClass(name);

            // 记录日志信息
            PerfCounter.getParentDelegationTime().addTime(t1 - t0);
            PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
            PerfCounter.getFindClasses().increment();
        }

        System.out.println("结束加载：c=" + c);

        if (resolve) {
            resolveClass(c);
        }

        return c;
    }
}
